package com.until;

import com.alibaba.excel.EasyExcel;
import com.constants.Constants;
import com.controller.MainController;
import com.entity.AllTask;
import com.tools.TaskListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.tools.BaseUntil.message;

/**
 * @author Kilon
 * @date 2022/3/22
 * @apiNote
 */
public class TaskManag {

    static List<AllTask> alltask = new ArrayList<>();
    //************************************新增数据************************************
    public static void create(String taskbiaotiVar, String taskinfoVar, String type) {
        create(taskbiaotiVar, taskinfoVar, type, "新建");
    }

    public static void create(String taskbiaotiVar, String taskinfoVar, String type, String nowtype) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        alltask = TaskListener.getAlltask();
        if (taskbiaotiVar.isEmpty() || taskinfoVar.isEmpty()) {
            message("请输入待办标题和详细描述!");
            return;
        }
        AllTask newTask = new AllTask();
        newTask.setId(String.valueOf(alltask.size() + 1));
        newTask.setTitle(taskbiaotiVar);
        newTask.setInfo(taskinfoVar);
        newTask.setCountpotato("0");
        newTask.setCountsleep("0");
        newTask.setMaketime(dateString);
        newTask.setFinishtime("");
        newTask.setNowtype(nowtype);
        newTask.setTasktype(type);
        newTask.setMsg("无备注");
        alltask.add(newTask);
        justSave(alltask);
        message("添加成功!");
    }
    //***********************************修改数据***************************************
    public static void updateTask(AllTask newTask) {
        alltask = TaskListener.getAlltask();
        for (AllTask task: alltask) {
            if (task.getId().equals(newTask.getId())) {
                Collections.replaceAll(alltask, task, newTask);
            }
        }
        Collections.sort(alltask);
        justSave(alltask);
    }


    //***************************工具用来保存数据的******************************
    public static void justSave(List<AllTask> alltask) {
        //String filePath = MainController.class.getClassLoader().getResource(Constants.fileName).getFile();
        EasyExcel.write(Constants.filePath, AllTask.class).sheet(Constants.fileName).doWrite(alltask);
    }
}
